package com.epfresh.supplier.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.epfresh.api.constant.AppSupplyRouterConstant;
import com.epfresh.api.entity.RequestEntityMapSupply;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.StatusEntity;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.global.BaseFragment;
import com.epfresh.api.http.HttpRequest;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.CashierInputFilter;
import com.epfresh.api.utils.CustomDialog;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.list.LoadMoreExpandableListView;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.supplier.R;
import com.epfresh.supplier.activity.ProductActivity;
import com.epfresh.supplier.activity.ProductAddActivity;
import com.epfresh.supplier.activity.ProductAddStockActivity;
import com.epfresh.supplier.activity.ProductPromotionActivity;
import com.epfresh.supplier.activity.ProductSecKillActivity;
import com.epfresh.supplier.activity.SpotGoodsSearchActivity;
import com.epfresh.supplier.adapter.SoldListAdapter;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.supplier.entity.ContentEntity;
import com.epfresh.supplier.entity.PriceSetting;
import com.epfresh.supplier.entity.ProductConfigs;
import com.epfresh.supplier.entity.Promotion;
import com.epfresh.supplier.entity.TagPager;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by wzh on 2016/5/4.
 */
public class SoldFragment extends BaseFragment implements LoadMoreExpandableListView.IXListViewListener, AdapterView.OnItemClickListener, SoldListAdapter.OnBottomClickListener {
    protected View mainView;
    protected View vException;
    protected TextView tvExceptionDescription;
    protected ImageView ivExceptionIcon;
    private ProgressBar pb;

    private LoadMoreExpandableListView mListView;
    private List<ProductConfigs> groupList = new ArrayList<>();

    private SoldListAdapter adapter;

    private int requestSucceedCount = 0;

    //上下架，1上架列表，2下架列表,0草稿,4审核
    public int type = 1;
    //1现货2散货
    public int saleType = 1;

    private TagPager tagPager = new TagPager();

    private int PAGE_SIZE = 10;


    public boolean isDc;

    @Override
    public String getBaseTag() {
        return null;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            type = savedInstanceState.getInt("type", 1);
        }
        return inflater.inflate(R.layout.fragment_sold,
                container, false);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putInt("type", type);
        super.onSaveInstanceState(outState);
    }

    public int getCurrentIndex() {
        FragmentActivity activity = getActivity();
        if (activity != null && activity instanceof ProductActivity) {
            return ((ProductActivity) activity).getCurrentIndex();
        }
        return -1;
    }

    @Override
    public void onViewCreated(View v, Bundle savedInstanceState) {
        super.onViewCreated(v, savedInstanceState);
        initHeadView(v);

        vException = v.findViewById(R.id.v_exception);
        mainView = v.findViewById(R.id.fragment_ptr_home_ptr_frame);
        initException();

        mListView = (LoadMoreExpandableListView) v.findViewById(R.id.listview);
        mListView.setXListViewListener(this);
        adapter = new SoldListAdapter(getActivity(), groupList, mListView);
        adapter.setType(type);

        adapter.setDc(isDc);
        adapter.setOnBottomClickListener(this);
        adapter.setOnNotifyDataSetChangedListener(new SoldListAdapter.OnNotifyDataSetChangedListener() {
            @Override
            public void OnNotifyDataSetChangedListener(int size) {
                if (size == 0) {
                    requestSucceedCount = 0;
                    showExceptionView(R.mipmap.product_no, "暂无商品，请添加", 1);
                } else {
                    showMainView();
                }
            }
        });

        adapter.setOnChildClickListener(new SoldListAdapter.OnChildClickListener() {
            @Override
            public void onChildClickListener(int position, int childPosition, Promotion promotion, int type) {
                if (promotion != null && position < groupList.size()) {
                    if (type == 1) {//编辑

                        String type1 = promotion.getType();
                        ProductConfigs productConfigs = groupList.get(position);

                        //1促销2秒杀
                        if ("1".equals(type1)) {
                            intoPromotion(promotion, productConfigs);
                        } else if ("2".equals(type1)) {
                            intoSecKill(promotion, productConfigs);
                        }
                    } else if (type == 0) {//结束活动
                        stopPromotion(promotion);
                    }
                }
            }
        });
        mListView.setAdapter(adapter);

        refresh();
    }

    private void intoPromotion(Promotion promotion, ProductConfigs productConfigs) {
        Intent intent = new Intent(getActivity(), ProductPromotionActivity.class);
//        intent.putExtra("chargeUnit", promotion.getChargeUnit());
//        intent.putExtra("incr", productAddEntity.getIncr());
//        intent.putExtra("moq", productAddEntity.getMoq());
        intent.putExtra("chargeUnit", productConfigs.getChargeUnit());
        intent.putExtra("incr", productConfigs.getIncr());
        intent.putExtra("moq", productConfigs.getMoq());
        intent.putExtra("productId", productConfigs.getId());
        intent.putExtra("inventory", productConfigs.getInventory());
        intent.putExtra("price", productConfigs.getPrice() + "");
        Log.e("id", "id:" + productConfigs.getId());
        if (promotion != null) {
            intent.putExtra("promotion", new Gson().toJson(promotion));
            if (type != 0)
                intent.putExtra("promotionStatus", promotion.getPromotionStatus());
        }
//        if (hasProductId()) {
//            intent.putExtra("isEdit", true);
//        }

        startActivityForResult(intent, 0x1948);
    }

    private void intoSecKill(Promotion promotion, ProductConfigs productConfigs) {
        Intent intent = new Intent(getActivity(), ProductSecKillActivity.class);
        intent.putExtra("chargeUnit", productConfigs.getChargeUnit());
        intent.putExtra("incr", productConfigs.getIncr());
        intent.putExtra("moq", productConfigs.getMoq());
        intent.putExtra("productId", productConfigs.getId());
        intent.putExtra("inventory", productConfigs.getInventory());
        intent.putExtra("price", productConfigs.getPrice() + "");

        if (promotion != null) {
            if (type != 0)
                intent.putExtra("promotionStatus", promotion.getPromotionStatus());
            intent.putExtra("promotion", new Gson().toJson(promotion));
        }
//        if (hasProductId()) {
//            intent.putExtra("isEdit", true);
//        }

        startActivityForResult(intent, 0x1947);
    }

    private void stopPromotion(Promotion promotion) {
        openStopDialog(promotion.getId());


    }

    Dialog dialog;

    private void openSelectPromotion(final ProductConfigs pcs) {
        dialog = null;
        if (dialog == null) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_promotion, null);

            view.findViewById(com.epfresh.api.R.id.tv_take_photo).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    intoPromotion(null, pcs);
                    dialog.dismiss();
                }
            });
            view.findViewById(com.epfresh.api.R.id.tv_get_photo).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    intoSecKill(null, pcs);
                    dialog.dismiss();
                }
            });
            view.findViewById(com.epfresh.api.R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
            dialog = new Dialog(getActivity(), com.epfresh.api.R.style.ActionSheetDialogStyle);
            dialog.setContentView(view);
            Window dialogWindow = dialog.getWindow();
            dialogWindow.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            lp.width = LocalDisplay.SCREEN_WIDTH_PIXELS;
            dialogWindow.setAttributes(lp);
        }
        dialog.show();
    }

    public boolean isDc() {
        return isDc;
    }

    public void setDc(boolean dc) {
        isDc = dc;
    }

    public void initException() {
        tvExceptionDescription = (TextView) vException.findViewById(R.id.tv_exception);
        ivExceptionIcon = (ImageView) vException.findViewById(R.id.iv_exception);
        pb = (ProgressBar) vException.findViewById(R.id.pb);
        tvExceptionDescription.setOnClickListener(this);
        ivExceptionIcon.setOnClickListener(this);
    }

    private PtrFrameLayout ptrFrameLayout;
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, mListView, header);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            refresh();
        }
    };

    private void initHeadView(View v) {
        ptrFrameLayout = (PtrFrameLayout) v.findViewById(R.id.fragment_ptr_home_ptr_frame);
        ptrFrameLayout.setPtrHandler(ptrHandler);
//        ptrFrameLayout.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                ptrFrameLayout.autoRefresh(true);
//            }
//        }, 200);
    }

    public void refreshWithHeader() {
//        ptrFrameLayout.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                ptrFrameLayout.autoRefresh(true);
//            }
//        }, 200);
        refresh();
    }

    private void requestActivityRefresh() {
        BaseActivity appActivity = getAppActivity();
        if (appActivity != null && appActivity instanceof ProductActivity) {
            ((ProductActivity) appActivity).refreshList();
        }

        if (appActivity != null && appActivity instanceof SpotGoodsSearchActivity) {
            ((SpotGoodsSearchActivity) appActivity).refreshList();
        }
    }

    public void refresh() {
        mListView.resetNoMore();
        requestProduct(0, PAGE_SIZE);
    }

    @Override
    public void onLoadMore() {

        int number = tagPager.getNumber();
        requestProduct(number + 1, PAGE_SIZE);
    }

    public void updateViewStatus(RequestTag requestTag) {
        ptrFrameLayout.refreshComplete();
        if (tagPager.isLast()) {
            mListView.noMore();
        } else {
            mListView.stopLoadMore();
        }
    }

    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.tv_exception:
            case R.id.iv_exception:
                onException((Integer) view.getTag());
                break;

        }
    }

    int currentPosition = -1;

    @Override
    public void onBottomClickListener(int position, int type) {
        currentPosition = position;
        if (type == 0) {//上下架
            openUpDownDialog(position);

        } else if (type == 8) {//编辑
            edit(position, this.type);
        } else if (type == 2) {//调价
            editPrice(position);
        } else if (type == 3) {//进入店铺详情

        } else if (type == 4) {//展开收起list

        } else if (type == 6) {//补货

            intoStock(position);

        } else if (type == 7) {//删除
            ProductConfigs productConfigs = groupList.get(position);
            String id = productConfigs.getId();

            delete(id);

        } else if (type == 1) {//活动
            ProductConfigs productConfigs = groupList.get(position);
            openSelectPromotion(productConfigs);
        } else if (type == 9) {//顶一顶
            ProductConfigs productConfigs = groupList.get(position);
            String id = productConfigs.getId();
            if (id != null && !"".equals(id))
                requestUpGoods(id);
        }

    }


    private void requestUpGoods(String id) {
        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(AppSupplyRouterConstant.cmd_store_product_top);
        RequestEntityMapSupply.putParameter("productId", id);
        request(RequestEntityMapSupply, AppSupplyRouterConstant.cmd_store_product_top, onProductUpRequestListener);

    }

    private OnRequestListener<StatusEntity> onProductUpRequestListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StatusEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {

            hideProgressDialog();
            StatusEntity responseElement = response.getResponseElement();
            String result = responseElement.getResult();
            if (result == null || "".equals(result)) {
                T.toast("置顶成功");
            } else {
                T.toast("" + result);
            }
//            if (responseElement.isSuccess()) {
//                T.toast("删除成功");
//            } else {
//                T.toast("删除失败");
//            }

        }
    };

    public void intoStock(int position) {
        Intent intent = new Intent(getAppActivity(), ProductAddStockActivity.class);
        ProductConfigs productConfigs = groupList.get(position);
        String id = productConfigs.getId();
        String chargeUnit = productConfigs.getChargeUnit();
        int type = productConfigs.getType();

        intent.putExtra("type", type + "");
        intent.putExtra("productId", id);
        intent.putExtra("chargeUnit", chargeUnit);

        startActivity(intent);
    }

    CustomDialog.Builder builder;

    private void openUpDownDialog(final int position) {
        if (builder == null) {
            builder = new CustomDialog.Builder(getContext());

        }
        String s = "";
        if (this.type == 1) {//上架列表
            s = "是否确认下架";
        } else {//下架列表
            s = "是否确认上架";
        }
        builder.setTitleVisible(false).setMessage(s)//设置显示的内容
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮
                    @Override
                    public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                        if (type == 1) {//上架列表
                            upDown(position);
                        } else {//下架列表
                            downUp(position);
                        }
                        dialog.dismiss();
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加返回按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {//响应事件
                dialog.dismiss();
            }

        });//在按键响应事件中显示此对话框

        builder.create().show();
    }

    private void inventoryDialog(StatusEntity responseElement, final int position, final String id, final int status, final String saleType) {


        if (responseElement == null) {
            return;
        }
        CustomDialog.Builder builder = new CustomDialog.Builder(getActivity());

        String s = "";
        final boolean isPormotionFail = responseElement.isPromotionFail();
        final boolean isSecKillFail = responseElement.isSeckillFail();
        if (isPormotionFail && isSecKillFail) {
            s = "库存数量小于当前待促销及秒杀活动数量之和，活动是否继续？";
        } else if (isPormotionFail && !isSecKillFail) {
            s = "库存数量小于当前促销数量，活动是否继续？";
        } else if (!isPormotionFail && isSecKillFail) {
            s = " 库存数量小于当前秒杀活动数量，活动是否继续？";
        }

        builder.setTitleVisible(false).setMessage(s);//设置显示的内容


        if (isSecKillFail) {
            builder.setPositiveButton("结束秒杀", new DialogInterface.OnClickListener() {//添加确定按钮
                @Override
                public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                    requestUpDown(position, id, status, saleType, true, 2);
                    dialog.dismiss();


                }
            });
        }
        if (isPormotionFail) {
            builder.setMidButton("结束促销", new DialogInterface.OnClickListener() {//添加确定按钮
                @Override
                public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                    requestUpDown(position, id, status, saleType, true, 1);
                    dialog.dismiss();


                }
            });
        }
        builder.setNegativeButton("继续", new DialogInterface.OnClickListener() {//添加返回按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {//响应事件
                requestUpDown(position, id, status, saleType, true, -1);
                dialog.dismiss();
            }

        });//在按键响应事件中显示此对话框

        builder.create().show();


    }

    //上架列表中下架按钮
    public void upDown(int position) {
        ProductConfigs productConfigs = groupList.get(position);
        String id = productConfigs.getId();
        int type = productConfigs.getType();
        requestUpDown(position, id, 2, type + "");

    }

    //下架列表中上架按钮
    public void downUp(int position) {
        ProductConfigs productConfigs = groupList.get(position);
        String id = productConfigs.getId();
        int type = productConfigs.getType();


        requestUpDown(position, id, 1, type + "", false, -1);
    }


    //上下架，1上架列表，2下架列表,0草稿,4审核
    public void edit(int position, int listType) {
        ProductConfigs productConfigs = groupList.get(position);
        String id = productConfigs.getId();
        int type = productConfigs.getType();
        Intent intent = new Intent(getContext(), ProductAddActivity.class);
        intent.putExtra("is_first", false);
        intent.putExtra("productId", id);
        intent.putExtra("listType", listType);
        Log.e("listType", listType + "");
        intent.putExtra(Constant.TYPE, type + "");
        if (getActivity() != null && getActivity() instanceof SpotGoodsSearchActivity) {
            intent.putExtra("isSpotSearch","isSpotSearch");
        }
        startActivityForResult(intent, 0x23);

    }

    public void editPrice(int position) {
        final ProductConfigs productConfigs = groupList.get(position);
        if (getActivity() == null) {
            return;
        }
        final Dialog dialog = new Dialog(getContext(), R.style.no_title_dialog);

        dialog.setContentView(R.layout.dialog_price_edit);
        final EditText ed = (EditText) dialog.findViewById(R.id.tv_moq);
        CashierInputFilter cashierInputFilter = new CashierInputFilter();
        cashierInputFilter.MAX_VALUE = 9999999;
        ed.setFilters(new InputFilter[]{cashierInputFilter});
        ed.setText(String.format("%.2f", productConfigs.getPrice()));
        ed.setSelection(ed.length());

        dialog.findViewById(R.id.negativeButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

        dialog.findViewById(R.id.positiveButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String s = ed.getText().toString();

                if (TextUtils.isEmpty(s)) {
                    T.toast("请输入价格");
                    return;
                }
                String id = productConfigs.getId();

                requestProductModify(id, s, productConfigs);
                dialog.dismiss();
            }
        });

        dialog.show();
//        int type = productConfigs.getType();
//        String id = productConfigs.getId();
//        List<ProductConfigsConfigs> configs = productConfigs.getConfigs();
//        if (configs == null) {
//            configs = new ArrayList<>();
//        }
//        String container = productConfigs.getProductChargeUnit();
//        String unit = productConfigs.getSpec();
//        if ("散货".equals(container)) {
//            container = unit;
//        }
//        productConfigs.setConfigs(configs );
//        Intent intent = new Intent(getContext(), PriceSettingActivity.class);
//        intent.putExtra("is_first", false);
//        intent.putExtra("productId", id);
//        intent.putExtra("ProductConfigsConfigs", new Gson().toJson(configs));
//        intent.putExtra("unit", unit);
//        intent.putExtra("container", container);
//        intent.putExtra(Constant.TYPE, type + "");
//
//        startActivityForResult(intent, 0x2);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //价格设置返回
        if (resultCode == Activity.RESULT_OK && requestCode == 0x2) {
            String productId = data.getStringExtra("productId");
            if (currentPosition > -1 && currentPosition < groupList.size()) {
                ProductConfigs productConfigs = groupList.get(currentPosition);

                if (!TextUtils.isEmpty(productId)) {
                    if (productId.equals(productConfigs.getId())) {
                        String s = data.getStringExtra(Constant.KEY_PRICE_LIST);
                        if (!TextUtils.isEmpty(s)) {
                            List<PriceSetting> priceSettings = new Gson().fromJson(s, new TypeToken<List<PriceSetting>>() {
                            }.getType());
                            if (priceSettings != null && priceSettings.size() > 0) {

                            } else {

                            }
                        } else {

                        }
                    }
                }
            }

            requestActivityRefresh();
        } else if (resultCode == Activity.RESULT_OK && requestCode == 0x23) {
            //编辑返回
            requestActivityRefresh();
        } else if (resultCode == Activity.RESULT_OK && (requestCode == 0x1947 || requestCode == 0x1948)) {

            requestActivityRefresh();
        }
    }

    public void onException(int tag) {
        refresh();
    }


    public void showMainView() {
        vException.setVisibility(View.GONE);
        mainView.setVisibility(View.VISIBLE);
    }

    public void showExceptionView(int imgSrc, String text, int exceptionType) {
        if (imgSrc > 0) {

        }
        pb.setVisibility(View.GONE);
        vException.setVisibility(View.VISIBLE);
        tvExceptionDescription.setVisibility(View.VISIBLE);
        ivExceptionIcon.setVisibility(View.VISIBLE);
        mainView.setVisibility(View.GONE);

        ivExceptionIcon.setImageResource(imgSrc);
        tvExceptionDescription.setText(text);
        tvExceptionDescription.setTag(exceptionType);
        ivExceptionIcon.setTag(exceptionType);
        tvExceptionDescription.setOnClickListener(this);
        ivExceptionIcon.setOnClickListener(this);
    }

    public void showProgressView() {

        pb.setVisibility(View.VISIBLE);
        vException.setVisibility(View.VISIBLE);
        tvExceptionDescription.setVisibility(View.GONE);
        ivExceptionIcon.setVisibility(View.GONE);
        mainView.setVisibility(View.GONE);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }

    public void requestProduct(int pageNumber, int pageSize) {
        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(AppSupplyRouterConstant.cmd_store_product_list4supplier);
        RequestEntityMapSupply.putParameter("status", type + "");
        RequestEntityMapSupply.putParameter("type", saleType + "");
        RequestEntityMapSupply.putParameter("pageNumber", pageNumber);
        RequestEntityMapSupply.putParameter("pageSize", pageSize);
        RequestEntityMapSupply.putParameter("storeId", BaseApplication.getInstance().getStoreId());
        if (getActivity() != null && getActivity() instanceof SpotGoodsSearchActivity) {
            if (!TextUtils.isEmpty(((SpotGoodsSearchActivity) getActivity()).getKeyword())) {
                RequestEntityMapSupply.putParameter("keyword", ((SpotGoodsSearchActivity) getActivity()).getKeyword());
            }
        }
        RequestTag requestTag = new RequestTag();
        requestTag.tag = AppSupplyRouterConstant.cmd_store_product_list4supplier;
        requestTag.action = pageNumber;
        request(RequestEntityMapSupply, requestTag, onProductRequestListener);
    }

    private OnRequestListener<ContentEntity<ProductConfigs>> onProductRequestListener = new OnRequestListener<ContentEntity<ProductConfigs>>() {
        @Override
        public ContentEntity<ProductConfigs> jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, new TypeToken<ContentEntity<ProductConfigs>>() {
            }.getType());
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            RequestTag requestTag = (RequestTag) tag;
            updateViewStatus(requestTag);
            if (requestSucceedCount == 0) {
                showExceptionView(R.mipmap.icon_error, BaseApplication.getDoc().getNetWeak(), HttpRequest.FAIL_NET_FAULT);
            }
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            if (requestSucceedCount == 0) {
                showExceptionView(R.mipmap.icon_error, arg + "", HttpRequest.FAIL_NET_FAULT);
            }
            RequestTag requestTag = (RequestTag) tag;
            updateViewStatus(requestTag);
        }

        @Override
        public void onStart(Object tag) {
            if (requestSucceedCount == 0) {
                showProgressView();
            }
        }

        @Override
        public void onResponse(ResponseEntity<ContentEntity<ProductConfigs>> response, Object tag) {

            //页面第一次调用网络请求接口并成功
            if (requestSucceedCount == 0) {
                showMainView();
            }
            requestSucceedCount++;
            RequestTag requestTag = (RequestTag) tag;
            ContentEntity<ProductConfigs> responseElement = response.getResponseElement();
            if (getActivity() != null && getActivity() instanceof SpotGoodsSearchActivity) {
                if (type == 0) {
                    ((SpotGoodsSearchActivity) getActivity()).draftCount = responseElement.getTotalElements();
                }
                if (type == 1) {
                    ((SpotGoodsSearchActivity) getActivity()).upCount = responseElement.getTotalElements();
                }
                if (type == 2) {
                    ((SpotGoodsSearchActivity) getActivity()).downCount = responseElement.getTotalElements();
                }
                ((SpotGoodsSearchActivity) getActivity()).setTabCount();
            }

            if (responseElement != null) {

                List<ProductConfigs> content = responseElement.getContent();

                if (requestTag.action == 0) {
                    groupList.clear();
                }
                groupList.addAll(content);
                adapter.notifyDataSetChanged();
                tagPager.setLast(responseElement.getLast());
                tagPager.setNumber(responseElement.getNumber());
                tagPager.setSize(responseElement.getSize());
                tagPager.setTotalElements(responseElement.getTotalElements());

            } else {

                T.toast("返回数据错误");
            }
            updateViewStatus(requestTag);
        }
    };


    //status 1上架，2下架
    public void requestUpDown(int position, String id, int status, String saleType) {
        requestUpDown(position, id, status, saleType, true, -1);
    }

    public void requestUpDown(int position, String id, int status, String saleType, boolean skip, int promotionType) {
        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_product_toggleStatus);
        RequestEntityMapSupply.putParameter("productSpecId", id);
        RequestEntityMapSupply.putParameter("status", status);
        RequestEntityMapSupply.putParameter("toggleStatus", true);
        RequestEntityMapSupply.putParameter("skip", skip);
        RequestEntityMapSupply.putParameter("storeId", BaseApplication.getInstance().getStoreId());

        if (promotionType != 1 && promotionType != 2) {

        } else {
            ArrayList<Integer> strings = new ArrayList<>();
            strings.add(promotionType);
            RequestEntityMapSupply.putParameter("promotionTypes", strings);

        }


        RequestTag requestTag = new RequestTag();
        requestTag.action = position;
        requestTag.tag = com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_product_toggleStatus;
        requestTag.arg2 = RequestEntityMapSupply;

        requestTag.arg1 = saleType + "";
        request(RequestEntityMapSupply, requestTag, onUpDownRequestListener);
    }

    private OnRequestListener<StatusEntity> onUpDownRequestListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StatusEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
//            if (type == 1) {//上架列表
//                getAppActivity().toast("下架失败");
//            } else if (type == 2) {//下架列表
//                getAppActivity().toast("上架失败");
//            }
            T.toast(BaseApplication.getDoc().getNetWeak());
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
//            if (type == 1) {//上架列表
//                getAppActivity().toast("下架失败");
//            } else if (type == 2) {//下架列表
//                getAppActivity().toast("上架失败");
//            }
            T.toast("" + arg);
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {
            hideProgressDialog();

            StatusEntity responseElement = response.getResponseElement();

            if (responseElement.isSuccess()) {
                if (type == 1) {//上架列表
                    getAppActivity().toast(BaseApplication.getDoc().getOffShelf());
                } else if (type == 2) {//下架列表

                    boolean isPreSale = false;
                    if (tag instanceof RequestTag) {
                        RequestTag t = (RequestTag) tag;
                        if ("2".equals(t.arg1)) {
                            isPreSale = true;
                        }
                    }
                    if (isPreSale) {
                        getAppActivity().toast("商品审核中");
                    } else {
                        getAppActivity().toast(BaseApplication.getDoc().getOnShelf());
                    }

                }
                RequestTag requestTag = (RequestTag) tag;
                groupList.remove(requestTag.action);
                //刷新列表
                requestActivityRefresh();
                adapter.notifyDataSetChanged();
            } else {
                RequestTag requestTag = (RequestTag) tag;
                Object arg2 = requestTag.arg2;
                Object arg1 = requestTag.arg1;

                if (responseElement.isPromotionOrSeckillFail() && arg2 instanceof RequestEntityMapSupply) {
                    RequestEntityMapSupply rem = (RequestEntityMapSupply) arg2;

                    String saleType = (String) arg1;
//                    RequestEntityMapSupply.putParameter("id", id);
//                    RequestEntityMapSupply.putParameter("status", status);
                    Object id = rem.gettParameter("id");
                    Object status = rem.gettParameter("status");
                    if (saleType != null && id != null && status != null && status instanceof Integer) {
                        inventoryDialog(responseElement, requestTag.action, id + "", (int) status, saleType);
                    }
                } else {
                    if (type == 1) {//上架列表
                        getAppActivity().toast("下架失败");
                    } else if (type == 2) {//下架列表
                        getAppActivity().toast("上架失败");
                    }
                }

            }
        }
    };

    private void requestProductModify(String productId, String price, ProductConfigs productConfigs) {

        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_product_modify);


        RequestEntityMapSupply.putParameter("storeId", BaseApplication.getInstance().getStoreId());
        RequestEntityMapSupply.putParameter("price", price);
        RequestEntityMapSupply.putParameter("id", productId);
        RequestEntityMapSupply.putParameter("storeId", BaseApplication.getInstance().getStoreId());
        RequestTag tag = new RequestTag();
        tag.tag = productConfigs;
        tag.arg1 = price;

        request(RequestEntityMapSupply, tag, onProductModifyRequestListener);

    }

    private OnRequestListener<StatusEntity> onProductModifyRequestListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StatusEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {

            hideProgressDialog();
            StatusEntity responseElement = response.getResponseElement();
            if (responseElement.isSuccess()) {


                if (tag instanceof RequestTag) {
                    ProductConfigs productConfigs = (ProductConfigs) ((RequestTag) tag).tag;
                    productConfigs.setPrice(Float.valueOf(((RequestTag) tag).arg1));
                }
                adapter.notifyDataSetChanged();
                T.toast("修改成功");
            } else {
                //没有数据
                T.toast("修改失败");

            }

        }
    };


    private void delete(final String productId) {

        if (getActivity() == null) {
            return;
        }
        CustomDialog.Builder builder = new CustomDialog.Builder(getActivity());

        String s = "是否删除";

        builder.setTitleVisible(false).setMessage(s)//设置显示的内容
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮
                    @Override
                    public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                        dialog.dismiss();
                        if (productId != null && !"".equals(productId)) {
                            List<String> ids = new ArrayList<>();
                            ids.add(productId);
                            requestProductDelete(ids);
                        }
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加返回按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {//响应事件
                dialog.dismiss();
            }

        });//在按键响应事件中显示此对话框

        builder.create().show();
    }

    private void requestProductDelete(List<String> ids) {
        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_product_delete);
        RequestEntityMapSupply.putParameter("ids", ids);
        RequestEntityMapSupply.putParameter("storeId", BaseApplication.getInstance().getStoreId());
        request(RequestEntityMapSupply, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_product_delete, onProductDeleteRequestListener);

    }

    private OnRequestListener<StatusEntity> onProductDeleteRequestListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StatusEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {

            hideProgressDialog();
            StatusEntity responseElement = response.getResponseElement();
            if (responseElement.isSuccess()) {
                T.toast("删除成功");
                refresh();
            } else {
                T.toast("删除失败");
            }

        }
    };

    private void requestPromotionStop(String id) {
        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_promotion_over);
        RequestEntityMapSupply.putParameter("id", id);
        RequestEntityMapSupply.putParameter("storeId", BaseApplication.getInstance().getStoreId());
        request(RequestEntityMapSupply, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_promotion_over, onPromotionStopRequestListener);

    }

    private OnRequestListener<StatusEntity> onPromotionStopRequestListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StatusEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {

            hideProgressDialog();
            StatusEntity responseElement = response.getResponseElement();
            if (responseElement.isSuccess()) {
                refresh();
            } else {

            }

        }
    };


    CustomDialog.Builder builderStop;

    private void openStopDialog(final String id) {
        if (builderStop == null) {
            builderStop = new CustomDialog.Builder(getContext());

        }
        String s = "是否结束活动";

        builderStop.setTitleVisible(false).setMessage(s)//设置显示的内容
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮
                    @Override
                    public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                        requestPromotionStop(id);
                        dialog.dismiss();
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加返回按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {//响应事件
                dialog.dismiss();
            }

        });//在按键响应事件中显示此对话框

        builderStop.create().show();
    }

}
